package com.nbcio.pm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nbcio.common.core.utils.MapstructUtils;
import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.pm.domain.PmTeamMember;
import com.nbcio.pm.domain.bo.PmTeamMemberBo;
import com.nbcio.pm.domain.vo.PmTeamMemberVo;
import com.nbcio.pm.mapper.PmTeamMemberMapper;
import com.nbcio.pm.service.IPmTeamMemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Collection;

/**
 * 团队成员Service业务层处理
 *
 * @author nbmade
 * @date 2025-01-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmTeamMemberServiceImpl implements IPmTeamMemberService {

    private final PmTeamMemberMapper baseMapper;

    /**
     * 查询团队成员
     */
    @Override
    public PmTeamMemberVo queryById(Long id){
        return baseMapper.selectPmTeamMemberById(id);
    }

    /**
     * 查询团队成员列表
     */
    @Override
    public TableDataInfo<PmTeamMemberVo> queryPageList(PmTeamMemberBo bo) {
        // 使用支持多用户ID显示的查询方法
        List<PmTeamMemberVo> list = baseMapper.selectPmTeamMemberListWithUsers(bo);
        // 手动分页
        int total = list.size();
        int start = (int) ((bo.getPageNum() - 1) * bo.getPageSize());
        int end = Math.min(start + bo.getPageSize(), total);
        List<PmTeamMemberVo> pageList = list.subList(start, end);
        
        Page<PmTeamMemberVo> result = new Page<>(bo.getPageNum(), bo.getPageSize(), total);
        result.setRecords(pageList);
        return TableDataInfo.build(result);
    }

    /**
     * 查询团队成员列表
     */
    @Override
    public List<PmTeamMemberVo> queryList(PmTeamMemberBo bo) {
        LambdaQueryWrapper<PmTeamMember> lqw = buildQueryWrapper(bo);
        return baseMapper.selectPmTeamMemberListWithUsers(bo);
    }

    /**
     * 根据条件查询团队成员列表
     */
    @Override
    public List<PmTeamMemberVo> queryListByCondition(PmTeamMemberBo bo) {
        LambdaQueryWrapper<PmTeamMember> lqw = buildQueryWrapper(bo);
        return baseMapper.selectPmTeamMemberList(bo);
    }

    private LambdaQueryWrapper<PmTeamMember> buildQueryWrapper(PmTeamMemberBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmTeamMember> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTenantId()), PmTeamMember::getTenantId, bo.getTenantId());
        lqw.eq(ObjectUtil.isNotNull(bo.getTeamId()), PmTeamMember::getTeamId, bo.getTeamId());
        // 支持按用户ID查询（可能是逗号分隔的多个ID）
        if (StringUtils.isNotBlank(bo.getUserId())) {
            if (bo.getUserId().contains(",")) {
                // 多个用户ID，使用IN查询
                String[] userIds = bo.getUserId().split(",");
                lqw.in(PmTeamMember::getUserId, (Object[]) userIds);
            } else {
                // 单个用户ID，使用精确匹配或包含匹配
                lqw.and(wrapper -> wrapper
                    .eq(PmTeamMember::getUserId, bo.getUserId())
                    .or()
                    .like(PmTeamMember::getUserId, bo.getUserId() + ",")
                    .or()
                    .like(PmTeamMember::getUserId, "," + bo.getUserId() + ",")
                    .or()
                    .like(PmTeamMember::getUserId, "," + bo.getUserId())
                );
            }
        }
        lqw.eq(ObjectUtil.isNotNull(bo.getRoleId()), PmTeamMember::getRoleId, bo.getRoleId());
        lqw.eq(ObjectUtil.isNotNull(bo.getJoinDate()), PmTeamMember::getJoinDate, bo.getJoinDate());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PmTeamMember::getStatus, bo.getStatus());
        lqw.eq(ObjectUtil.isNotNull(bo.getIsActive()), PmTeamMember::getIsActive, bo.getIsActive());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), PmTeamMember::getRemark, bo.getRemark());
        return lqw;
    }

    /**
     * 新增团队成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PmTeamMemberBo bo) {
        PmTeamMember add = MapstructUtils.convert(bo, PmTeamMember.class);
        
        // 处理多用户ID：优先使用userIds，如果为空则使用userId
        if (bo.getUserIds() != null && !bo.getUserIds().isEmpty()) {
            // 使用userIds列表
            String userIdsStr = bo.getUserIds().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
            add.setUserId(userIdsStr);
        } else if (bo.getUserId() != null && !bo.getUserId().isEmpty()) {
            // 使用单个userId
            add.setUserId(bo.getUserId());
        }
        
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改团队成员
     */
    @Override
    public Boolean updateByBo(PmTeamMemberBo bo) {
        PmTeamMember update = MapstructUtils.convert(bo, PmTeamMember.class);
        
        // 处理多用户ID：优先使用userIds，如果为空则使用userId
        if (bo.getUserIds() != null && !bo.getUserIds().isEmpty()) {
            // 使用userIds列表
            String userIdsStr = bo.getUserIds().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
            update.setUserId(userIdsStr);
        } else if (bo.getUserId() != null && !bo.getUserId().isEmpty()) {
            // 使用单个userId
            update.setUserId(bo.getUserId());
        }
        
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmTeamMember entity){
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除团队成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量添加团队成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchInsertByBo(PmTeamMemberBo bo) {
        if (bo.getUserIds() != null && !bo.getUserIds().isEmpty()) {
            for (Long userId : bo.getUserIds()) {
                PmTeamMember member = new PmTeamMember();
                member.setTeamId(bo.getTeamId());
                member.setUserId(String.valueOf(userId));
                member.setRoleId(bo.getRoleId());
                member.setJoinDate(bo.getJoinDate());
                member.setStatus(bo.getStatus());
                member.setIsActive(bo.getIsActive());
                member.setRemark(bo.getRemark());
                member.setTenantId(bo.getTenantId());
                baseMapper.insert(member);
            }
            return true;
        }
        return false;
    }
}
